import { isNaN } from 'lodash';

const isValidNum = (num, { mode = 'thanZero' } = {}) => {
  let newNum = typeof num === 'string' ? num.trim() : num;
  if (!newNum && typeof newNum !== 'number') {
    return null;
  }
  newNum = +newNum;
  if (mode === 'thanZero') {
    return newNum > 0;
  }

  return !isNaN(newNum);
};

// 获取文件校验结果信息
export const getTaskFileValidInfo = result => {
  if (!(result?.length > 0)) {
    return { errMsg: '文件商品数据为空', isValid: false };
  }
  let errMsg = '';
  const isValidFail = result.some((item, index) => {
    const rowText = `第${index + 2}行`;
    if (!item.channelCode) {
      errMsg = `${rowText}渠道编码为空`;
      return true;
    }
    if (!item.goodsCode) {
      errMsg = `${rowText}商品编码为空`;
      return true;
    }
    if (!(item.newChannelPrice || item.limitFrequency || item.limitNum || item.newActivityPrice || item.activityPriceLimit)) {
      errMsg = `${rowText}没有设置调价需求`;
      return true;
    }
    if (!isValidNum(item.newChannelPrice)) {
      errMsg = `${rowText}调原价必须为大于0的数字`;
      return true;
    }
    if (!isValidNum(item.limitFrequency)) {
      errMsg = `${rowText}限购频率必须为大于0的数字`;
      return true;
    }
    if (!isValidNum(item.limitNum)) {
      errMsg = `${rowText}限购数量必须为大于0的数字`;
      return true;
    }
    if (!isValidNum(item.newActivityPrice)) {
      errMsg = `${rowText}调特价必须为大于0的数字`;
      return true;
    }
    if (!isValidNum(item.activityPriceLimit)) {
      errMsg = `${rowText}特价限购必须为大于0的数字`;
      return true;
    }
    if (!isValidNum(item.costPrice, { mode: 'notNaN' })) {
      errMsg = `${rowText}成本价不是数字`;
      return true;
    }
    if (!isValidNum(item.channelPrice, { mode: 'notNaN' })) {
      errMsg = `${rowText}商品原价不是数字`;
      return true;
    }
    if (!isValidNum(item.competeChannelPrice, { mode: 'notNaN' })) {
      errMsg = `${rowText}竞对原价最低价不是数字`;
      return true;
    }
    if (!isValidNum(item.competeActivityPrice, { mode: 'notNaN' })) {
      errMsg = `${rowText}竞对特价最低价不是数字`;
      return true;
    }
    if (!isValidNum(item.competeMaxSales, { mode: 'notNaN' })) {
      errMsg = `${rowText}竞对最高销量不是数字`;
      return true;
    }
    if (!isValidNum(item.cellularSales, { mode: 'notNaN' })) {
      errMsg = `${rowText}蜂窝总销量不是数字`;
      return true;
    }
    if (!isValidNum(item.retailPrice, { mode: 'notNaN' })) {
      errMsg = `${rowText}商品原价不是数字`;
      return true;
    }
    if (!isValidNum(item.activityPrice, { mode: 'notNaN' })) {
      errMsg = `${rowText}商品特价不是数字`;
      return true;
    }
    if (!isValidNum(item.salesRank, { mode: 'notNaN' })) {
      errMsg = `${rowText}销售排名不是数字`;
      return true;
    }
    if (!isValidNum(item.monthSales, { mode: 'notNaN' })) {
      errMsg = `${rowText}月售不是数字`;
      return true;
    }
    return false;
  });

  return {
    isValid: !isValidFail,
    errMsg,
  };
};
